//导入axios
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

//导入token工具包
import {
  getToken
} from './token.js'
//导入MessageBox
import {
  MessageBox
} from 'element-ui'
//导入router
import
router
from '@/router/index.js'

//创建instance
const instance = axios.create({
  baseURL: 'https://autumnfish.cn/bignews/api/v1',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [
    function (data, headers) {
      if (data instanceof FormData) {
        return data
      } else {
        //把json格式参数转为key=value格式
        let sp = new URLSearchParams()
        for (let key in data) {
          sp.append(key, data[key])
        }
        return sp
      }
    }
  ]
})

//添加请求拦截器

instance.interceptors.request.use(
  function (config) {
    //在发送请求之前做些什么
    //默认请求头中发token
    if (getToken()) {
      config.headers.Authorization = getToken().token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

//添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    //对响应数据做点什么
    return response
  },
  function (error) {
    if (error.response.status == 403) {
      //弹窗提示
      MessageBox.alert('请先登录', '友情提示', {
        confirmButtonText: '确定',
        callback: action => {
          //跳转登录页
          router.push('/login')
        }
      })
    }
    return Promise.reject(error)
  }
)

//导出instance
export default instance
